<template>
  <div class="menu-list">
    <header class="header">
      <div class="search-section">
        <el-input
          v-model="keyword"
          placeholder="请输入菜单名称查询"
          @input="handleSearch"
          clearable
          style="width: 300px;"
        ></el-input>
      </div>
      <div class="btn-group">
        <ButtonPermission code="menu:add" mode="disable">
          <template #default="{ disabled }">
            <el-button 
              type="primary" 
              icon="el-icon-plus" 
              :disabled="disabled"
              @click="!disabled && addMenu()"
            >
              新增菜单
            </el-button>
          </template>
        </ButtonPermission>
      </div>
    </header>
    <main class="main table-container">
      <div class="table-wrapper">
        <el-table 
          ref="menuTable" 
          :data="menuList" 
          stripe 
          border 
          row-key="id"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          default-expand-all
          class="responsive-table"
        >
          <el-empty
            v-if="!loading && menuList.length === 0"
            description="暂无数据"
            :image-size="100"
          ></el-empty>
          <el-table-column
            prop="menu_name"
            label="菜单名称"
            min-width="150"
            align="left"
          >
            <template #default="scope">
              <i :class="scope.row.menu_icon" style="margin-right: 8px;"></i>
              <span>{{ scope.row.menu_name }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="menu_path"
            label="菜单路径"
            min-width="200"
            align="left"
          ></el-table-column>
          <el-table-column
            prop="parent_id"
            label="父菜单"
            min-width="120"
            align="center"
          >
            <template #default="scope">
              <span v-if="scope.row.parent_id === 0">顶级菜单</span>
              <span v-else>{{ getParentMenuName(scope.row.parent_id) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="sort_order"
            label="排序"
            min-width="80"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="status"
            label="状态"
            min-width="80"
            align="center"
          >
            <template #default="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                {{ scope.row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="menu_type"
            label="菜单类型"
            min-width="100"
            align="center"
          >
            <template #default="scope">
              <el-tag :type="scope.row.menu_type === 1 ? 'primary' : 'success'">
                {{ scope.row.menu_type === 1 ? '菜单项' : scope.row.menu_type === 2 ? '功能按钮' : '未知' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="platform"
            label="平台"
            min-width="100"
            align="center"
          >
            <template #default="scope">
              <el-tag :type="scope.row.platform === 2 ? 'success' : 'info'">
                {{ scope.row.platform === 1 ? '前端' : scope.row.platform === 2 ? '管理后台' : scope.row.platform === 3 ? '小程序端' : '未知' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="remark"
            label="备注"
            min-width="150"
            align="left"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            label="操作"
            min-width="150"
            align="center"
            fixed="right"
          >
            <template #default="scope">
              <ButtonPermission code="menu:edit" mode="disable">
                <template #default="{ disabled }">
                  <span class="btn" :class="{ disabled: disabled }" @click="!disabled && editMenu(scope.row)">编辑</span>
                </template>
              </ButtonPermission>
              <ButtonPermission code="menu:delete" mode="disable">
                <template #default="{ disabled }">
                  <span class="btn" :class="{ disabled: disabled }" @click="!disabled && deleteMenu(scope.row)">删除</span>
                </template>
              </ButtonPermission>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </main>
    
    <!-- 编辑/添加菜单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="menuForm"
        :model="menuForm"
        :rules="menuRules"
        label-width="100px"
      >
        <el-form-item label="菜单类型" prop="menu_type">
          <el-radio-group v-model="menuForm.menu_type" @change="handleMenuTypeChange">
            <el-radio :label="1">菜单项</el-radio>
            <el-radio :label="2">功能按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单名称" prop="menu_name">
          <el-input v-model="menuForm.menu_name" placeholder="请输入菜单名称"></el-input>
        </el-form-item>
        <el-form-item label="菜单路径" prop="menu_path" v-if="menuForm.menu_type === 1">
          <el-input v-model="menuForm.menu_path" placeholder="请输入菜单路径，如：/homepage/menu"></el-input>
        </el-form-item>
        <el-form-item label="按钮标识" prop="menu_path" v-else>
          <el-input 
            v-model="menuForm.menu_path" 
            placeholder="请输入按钮标识，如：add、edit、delete、export、import"
          >
            <template #append>
              <el-dropdown @command="handleButtonCommand">
                <el-button>常用按钮</el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="add">添加 (add)</el-dropdown-item>
                    <el-dropdown-item command="edit">编辑 (edit)</el-dropdown-item>
                    <el-dropdown-item command="delete">删除 (delete)</el-dropdown-item>
                    <el-dropdown-item command="export">导出 (export)</el-dropdown-item>
                    <el-dropdown-item command="import">导入 (import)</el-dropdown-item>
                    <el-dropdown-item command="view">查看 (view)</el-dropdown-item>
                    <el-dropdown-item command="search">搜索 (search)</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="菜单图标" prop="menu_icon" v-if="menuForm.menu_type === 1">
          <el-input v-model="menuForm.menu_icon" placeholder="请输入图标类名，如：el-icon-menu">
            <template #prefix>
              <i :class="menuForm.menu_icon" v-if="menuForm.menu_icon"></i>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="父菜单" prop="parent_id" :rules="menuForm.menu_type === 2 ? [{ required: true, message: '功能按钮必须选择父菜单', trigger: 'change' }] : []">
          <el-select 
            v-model="menuForm.parent_id" 
            :placeholder="menuForm.menu_type === 2 ? '功能按钮必须选择父菜单' : '请选择父菜单'" 
            clearable
          >
            <el-option
              v-if="menuForm.menu_type === 1"
              label="顶级菜单"
              :value="0"
            ></el-option>
            <el-option
              v-for="menu in availableParentMenus"
              :key="menu.id"
              :label="menu.menu_name"
              :value="menu.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort_order">
          <el-input-number v-model="menuForm.sort_order" :min="0" :max="9999" style="width: 100%;"></el-input-number>
        </el-form-item>
        <el-form-item label="平台" prop="platform">
          <el-radio-group v-model="menuForm.platform">
            <el-radio :label="1">前端</el-radio>
            <el-radio :label="2">管理后台</el-radio>
            <el-radio :label="3">小程序端</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="menuForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="menuForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { debounce } from '@/utils/utils';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
  name: 'MenuList',
  data() {
    return {
      menuList: [],
      allMenuList: [], // 所有菜单（扁平化，用于查找父菜单）
      parentMenuList: [], // 可作为父菜单的列表（顶级菜单）
      loading: false,
      keyword: '',
      
      // 对话框相关
      dialogVisible: false,
      dialogTitle: '新增菜单',
      menuForm: {
        id: null,
        menu_name: '',
        menu_path: '',
        menu_icon: '',
        menu_type: 1, // 菜单类型：1-菜单项，2-功能按钮
        parent_id: 0,
        sort_order: 0,
        platform: 2, // 平台：1-前端，2-管理后台，3-小程序端，默认管理后台
        status: 1,
        remark: '',
      },
      menuRules: {
        menu_name: [
          { required: true, message: '请输入菜单名称', trigger: 'blur' }
        ],
        menu_path: [
          { required: true, message: '请输入菜单路径或按钮标识', trigger: 'blur' }
        ],
        menu_type: [
          { required: true, message: '请选择菜单类型', trigger: 'change' }
        ],
        platform: [
          { required: true, message: '请选择平台', trigger: 'change' }
        ],
      },
    };
  },
  computed: {
    // 获取可用的父菜单列表（根据菜单类型过滤）
    availableParentMenus() {
      // 如果是功能按钮，可以选择所有菜单项类型的菜单作为父菜单
      if (this.menuForm.menu_type === 2) {
        // 从扁平化的所有菜单列表中获取菜单项类型（递归获取所有菜单项）
        const getMenuItems = (menus) => {
          const result = [];
          menus.forEach(menu => {
            // 只包含菜单项类型（menu_type === 1 或 undefined，兼容旧数据）
            if (!menu.menu_type || menu.menu_type === 1) {
              result.push({
                id: menu.id,
                menu_name: menu.menu_name,
                parent_id: menu.parent_id,
              });
            }
            if (menu.children && menu.children.length > 0) {
              result.push(...getMenuItems(menu.children));
            }
          });
          return result;
        };
        // 从树形结构中获取所有菜单项
        const allMenuItems = getMenuItems(this.menuList);
        // 排除当前正在编辑的菜单（避免自己作为自己的父菜单）
        const filtered = allMenuItems.filter(menu => menu.id !== this.menuForm.id);
        // 如果没有菜单项，返回空数组，避免显示"顶级菜单"选项
        return filtered.length > 0 ? filtered : [];
      }
      // 如果是菜单项，显示所有顶级菜单
      return this.parentMenuList.filter(menu => menu.id !== this.menuForm.id);
    },
  },
  created() {
    this.getMenuList();
    // 初始化搜索防抖
    this._debouncedSearch = debounce(() => {
      this.filterMenuList();
    }, 300);
  },
  methods: {
    // 获取菜单列表
    async getMenuList() {
      try {
        this.loading = true;
        const { F_responseNo, F_menu_list } = await this.$api.getAllMenus();
        if (F_responseNo === 10000 && F_menu_list) {
          console.log('获取到的菜单数据:', F_menu_list);
          // 确保数据是数组格式
          const menuData = Array.isArray(F_menu_list) ? F_menu_list : [];
          this.allMenuList = this.flattenMenuList(menuData);
          this.menuList = menuData;
          this.updateParentMenuList();
          console.log('处理后的菜单列表:', this.menuList);
          console.log('扁平化菜单列表:', this.allMenuList);
        } else {
          ElMessage.error('获取菜单列表失败');
        }
      } catch (error) {
        console.error('获取菜单列表失败:', error);
        ElMessage.error('获取菜单列表失败');
      } finally {
        this.loading = false;
      }
    },
    
    // 扁平化菜单列表（用于查找）
    flattenMenuList(menus, result = []) {
      menus.forEach(menu => {
        result.push({
          id: menu.id,
          menu_name: menu.menu_name,
          menu_path: menu.menu_path,
          parent_id: menu.parent_id,
        });
        if (menu.children && menu.children.length > 0) {
          this.flattenMenuList(menu.children, result);
        }
      });
      return result;
    },
    
    // 更新父菜单列表（只显示顶级菜单）
    updateParentMenuList() {
      this.parentMenuList = this.allMenuList.filter(menu => menu.parent_id === 0);
    },
    
    // 处理菜单类型切换
    handleMenuTypeChange(value) {
      // 如果切换到功能按钮，且当前选择的是"顶级菜单"（parent_id=0），则清空父菜单选择
      if (value === 2 && this.menuForm.parent_id === 0) {
        this.menuForm.parent_id = null;
      }
      // 如果切换到菜单项，可以重置为顶级菜单
      if (value === 1 && this.menuForm.parent_id === null) {
        this.menuForm.parent_id = 0;
      }
    },
    
    // 处理按钮标识快捷选择
    handleButtonCommand(command) {
      this.menuForm.menu_path = command;
    },
    
    // 获取父菜单名称
    getParentMenuName(parentId) {
      const parent = this.allMenuList.find(menu => menu.id === parentId);
      return parent ? parent.menu_name : '-';
    },
    
    // 搜索菜单
    handleSearch() {
      this._debouncedSearch();
    },
    
    // 过滤菜单列表
    filterMenuList() {
      if (!this.keyword) {
        this.getMenuList();
        return;
      }
      
      const keyword = this.keyword.toLowerCase();
      const filterMenu = (menus) => {
        const result = [];
        menus.forEach(menu => {
          const match = menu.menu_name.toLowerCase().includes(keyword) ||
                       menu.menu_path.toLowerCase().includes(keyword);
          const children = menu.children && menu.children.length > 0 
            ? filterMenu(menu.children) 
            : [];
          
          if (match || children.length > 0) {
            result.push({
              ...menu,
              children: children.length > 0 ? children : menu.children
            });
          }
        });
        return result;
      };
      
      this.menuList = filterMenu(this.allMenuList.filter(m => m.parent_id === 0).map(m => {
        // 重新构建树形结构
        const buildTree = (parentId) => {
          return this.allMenuList
            .filter(m => m.parent_id === parentId)
            .map(m => ({
              ...m,
              children: buildTree(m.id)
            }));
        };
        return {
          ...m,
          children: buildTree(m.id)
        };
      }));
    },
    
    // 新增菜单
    addMenu() {
      this.dialogTitle = '新增菜单';
      this.menuForm = {
        id: null,
        menu_name: '',
        menu_path: '',
        menu_icon: 'el-icon-menu',
        menu_type: 1, // 默认菜单项
        parent_id: 0,
        sort_order: 0,
        platform: 2, // 默认管理后台
        status: 1,
        remark: '',
      };
      this.dialogVisible = true;
    },
    
    // 编辑菜单
    editMenu(row) {
      this.dialogTitle = '编辑菜单';
      this.menuForm = {
        id: row.id,
        menu_name: row.menu_name,
        menu_path: row.menu_path,
        menu_icon: row.menu_icon || 'el-icon-menu',
        menu_type: row.menu_type !== undefined ? row.menu_type : 1,
        parent_id: row.parent_id || 0,
        sort_order: row.sort_order || 0,
        platform: row.platform !== undefined ? row.platform : 2,
        status: row.status !== undefined ? row.status : 1,
        remark: row.remark || '',
      };
      this.dialogVisible = true;
    },
    
    // 删除菜单
    async deleteMenu(row) {
      try {
        await ElMessageBox.confirm(
          `确定要删除菜单"${row.menu_name}"吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        );
        
        const { F_responseNo, F_responseMsg } = await this.$api.deleteMenu({
          F_menu_id: row.id
        });
        
        if (F_responseNo === 10000) {
          ElMessage.success('删除成功');
          this.getMenuList();
          // 菜单删除后，刷新按钮权限
          try {
            await this.$store.dispatch('user/fetchAllButtonPermissions');
            console.log('菜单删除后，按钮权限已刷新');
          } catch (error) {
            console.error('刷新按钮权限失败:', error);
          }
        } else {
          ElMessage.error(F_responseMsg || '删除失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除菜单失败:', error);
          ElMessage.error('删除失败');
        }
      }
    },
    
    // 提交表单
    async handleSubmit() {
      try {
        await this.$refs.menuForm.validate();
        
        const params = {
          F_menu_name: this.menuForm.menu_name,
          F_menu_path: this.menuForm.menu_path,
          F_menu_icon: this.menuForm.menu_type === 1 ? this.menuForm.menu_icon : '', // 功能按钮不需要图标
          F_parent_id: this.menuForm.parent_id,
          F_sort_order: this.menuForm.sort_order,
          F_menu_type: this.menuForm.menu_type, // 菜单类型：1-菜单项，2-功能按钮
          F_platform: this.menuForm.platform, // 平台：1-前端，2-管理后台，3-小程序端
          F_status: this.menuForm.status,
          F_remark: this.menuForm.remark,
        };
        
        let response;
        if (this.menuForm.id) {
          // 更新
          params.F_menu_id = this.menuForm.id;
          response = await this.$api.updateMenu(params);
        } else {
          // 新增
          response = await this.$api.createMenu(params);
        }
        
        if (response.F_responseNo === 10000) {
          ElMessage.success(this.menuForm.id ? '更新成功' : '创建成功');
          this.dialogVisible = false;
          this.getMenuList();
          // 菜单修改后，刷新按钮权限
          try {
            await this.$store.dispatch('user/fetchAllButtonPermissions');
            console.log('菜单修改后，按钮权限已刷新');
          } catch (error) {
            console.error('刷新按钮权限失败:', error);
          }
        } else {
          ElMessage.error(response.F_responseMsg || '操作失败');
        }
      } catch (error) {
        if (error !== false) {
          console.error('提交失败:', error);
        }
      }
    },
    
    // 关闭对话框
    handleDialogClose() {
      this.$refs.menuForm?.resetFields();
    },
  },
};
</script>

<style lang="less" scoped>
.menu-list {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .search-section {
      display: flex;
      gap: 10px;
    }
    
    .btn-group {
      display: flex;
      gap: 10px;
    }
  }
  
  .main {
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    
    .table-wrapper {
      flex: 1;
      overflow: auto;
    }
  }
  
  .btn {
    color: #009cff;
    cursor: pointer;
    margin-right: 15px;
    transition: color 0.3s;
    
    &:hover:not(.disabled) {
      text-decoration: underline;
    }
    
    &:last-child {
      margin-right: 0;
    }
    
    &.disabled {
      color: #c0c4cc;
      cursor: not-allowed;
      opacity: 0.6;
      &:hover {
        text-decoration: none;
      }
    }
  }
}
</style>

